jQuery Mask Plugin

A jQuery Plugin to make masks on form fields and html elements.

Demonstrations

12345678909



Code Samples

Basic Examples

$(document).ready(function(){
  $('.date').mask('11/11/1111');
  $('.time').mask('00:00:00');
  $('.date_time').mask('99/99/9999 00:00:00');
  $('.cep').mask('99999-999');
  $('.phone').mask('9999-9999');
  $('.phone_with_ddd').mask('(99) 9999-9999');
  $('.phone_us').mask('(999) 999-9999');
  $('.mixed').mask('AAA 000-S0S');
  $('.cpf').mask('999.999.999-99', {reverse: true});
  $('.money').mask('000.000.000.000.000,00', {reverse: true});
  $('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': "[0-9]?"}});
);

Callback Examples

var options =  { onComplete: function(cep) {
  alert('Mask is done!:' + cep);
},
onKeyPress: function(cep, event, currentField, options){
  console.log('An key was pressed!:', cep, ' event: ', event, 
              'currentField: ', currentField, ' options: ', options);
}};

$('.cep_with_callback').mask('00000-000', options);
      

On-the-fly mask change

var options =  {onKeyPress: function(cep){
  var masks = ['00000-000', '0-00-00-00'];
    mask = (cep.length>7) ? masks[1] : masks[0];
  $('.crazy_cep').mask(mask, this);
}};

$('.crazy_cep').mask('00000-000', options);
  

Mask as a function

var SaoPauloCelphoneMask = function(phone, e, currentField, options){
  return phone.match(/^(\(?11\)? ?9(5[0-9]|6[0-9]|7[01234569]|8[0-9]|9[0-9])[0-9]{1})/g) ? 
  '(00) 00000-0000' : '(00) 0000-0000';
};

$(".sp_celphones").mask(SaoPauloCelphoneMask);
    

Customization

Teach to jQuery Mask Plugin how to apply your mask:

// now the digit 0 on your mask pattern will be interpreted 
// as valid characters like 0,1,2,3,4,5,6,7,8,9 and *
$('.your-field').mask('00/00/0000', {'translation': {0: '[0-9*]'}});
    
By default, jQuery Mask Plugin only reconizes the logical digit A (Numbers and Letters) and S (A-Za-z) but you can extend or modify this behaviour by telling to jQuery Mask Plugin how to interpret those logical digits.

$('.your-field').mask('AA/SS/YYYY', {'translation': 
                                      {A: '[A-Za-z0-9]', S: '[A-Za-z]',  Y: '[0-9]'}
                                    });
    
Now jQuery Mask Plugin knows the logic digit Y and you can create you own pattern.

Optional digits


You can also tell to jQuery Mask which digit is optional, to create a IP mask for example:

// way 1
$('.ip_address').mask('0{1,3}.0{1,3}.0{1,3}.0{1,3}');
// way 2
$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation:  {'Z': "[0-9]?"}});
Now, all Z digits in your masks is optional.

Removing the mask

$('.date').data('mask').remove();

Default Mask Legend